
/*
g++ test_async_efficiency.cpp -pthread
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>

// c++ program that demonstrates async
// library for std::cout
#include <iostream>
//library for std::async and std::future
#include <future>
// check whether it is prime number or not
//parameter is the number that has to be checked
bool fnprime (int num)
{
    // std::cout << "Process started. . . Just wait. . . \n";
//loop starts here
    for ( int i = 2 ; i < num ; ++i )
//if the mod is 0, return false, else return zero
        if (num % i == 0)
        {
            return false ;
        }
    return true ;
}

//main method
int main ()
{
   struct timeval time;

    /* 获取时间，理论到us */
    gettimeofday(&time, NULL);
    //printf("========== s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));
    long msec = time.tv_sec*1000 + time.tv_usec/1000;

#define COUNTS  1000

    for (int i = 0;  i < COUNTS;  i++) {
         // call the function fnprime() asynchronously
        std::future<bool> fobj = std::async(std::launch::async, fnprime, 4);

        std::future_status status;
        do {
            status = fobj.wait_for(std::chrono::seconds(1));

            /*
            if (status == std::future_status::deferred) {
                std::cout << "deferred" << std::endl;
            } else if (status == std::future_status::timeout) {
                std::cout << "timeout" << std::endl;
            } else if (status == std::future_status::ready) {
                std::cout << "ready!" << std::endl;
            }
            */

        } while (status != std::future_status::ready);

        /*
        //print the line to show the status
        std::cout << "check whether the number 4 is prime or not . . \n";
        */

        //waits for the the function fnprime to return
        bool bobj = fobj.get();

        /*
        //prints the result
        if (bobj) std::cout << "The number given is prime . . .  ! \n";
        else std::cout << "The number given is not prime . . .  ! \n\n";
        */

       /* 重新获取 */
        gettimeofday(&time, NULL);
        //printf("========== s: %ld, ms: %ld\n", time.tv_sec, (time.tv_sec*1000 + time.tv_usec/1000));
    }

    msec = time.tv_sec*1000 + time.tv_usec/1000 - msec;
    printf("=~~~~~~~~~~~~~~ ms: %ld  one: %f\n", msec, (double)msec / COUNTS);

    return 0;
}
